<template>
  <div class="registerBox">
    <h2>加入我们</h2>
    <div>
      <van-divider>
        <div class="tabs">
          <span :class="[{ 'curTab': curTab === 1 }, 'tabIn', 'fs26', 'c-666']" @click="handleLoginType(1)">账号注册</span>
          <span :class="[{ 'curTab': curTab === 2 }, 'tabIn', 'fs26', 'c-666']"
            @click="handleLoginType(2)">手机快捷注册</span>
        </div>
      </van-divider>
      <van-form @submit="onSubmit" ref="formRef">
        <van-cell-group inset v-if="curTab === 1">
          <van-field v-model="formData.account" name="account" label="账号" placeholder="请输入账号" label-align="top"
            :rules="[{ required: true, message: '请填写账号' }, { validator: accountRules }]" />
          <van-field v-model="formData.password" :type="showPas ? 'text' : 'password'" name="password" label="密码"
            placeholder="请输入密码，8-20位字符" label-align="top"
            :rules="[{ required: true, message: '请填写密码' }, { validator: passwordRules }]">
            <template #right-icon>
              <van-icon :name="!showPas ? 'eye-o' : 'closed-eye'" @click="showPas = !showPas" />
            </template>
          </van-field>
          <van-field v-model="formData.email" name="email" label="邮箱" placeholder="请输入邮箱" label-align="top"
            :rules="[{ required: true, message: '请填写邮箱' }, { validator: emailRules }]" />
          <van-field v-model="formData.code" center clearable label="验证码" placeholder="请输入验证码" label-align="top"
            :rules="[{ required: true, message: '请填写验证码' }, { validator: codeRules }]">
            <template #button>
              <van-button size="small" type="primary" :disabled="codeInfo.isCodeSent" @click="sendCode">{{
                codeInfo.timer ? `${codeInfo.codeTime}秒` : '获取验证码' }}</van-button>
            </template>
          </van-field>
        </van-cell-group>

        <van-cell-group inset v-if="curTab === 2">
          <van-field v-model="formData.phone" name="phone" label="手机号" placeholder="请输入手机号" label-align="top"
            :rules="[{ required: true, message: '请填写手机号' }, { validator: phoneRules }]" />
          <van-field v-model="formData.password" :type="showPas ? 'text' : 'password'" name="password" label="密码"
            placeholder="请输入密码，8-20位字符" label-align="top"
            :rules="[{ required: true, message: '请填写密码' }, { validator: passwordRules }]">
            <template #right-icon>
              <van-icon :name="!showPas ? 'eye-o' : 'closed-eye'" @click="showPas = !showPas" />
            </template>
          </van-field>
          <van-field v-model="formData.code" center clearable label="验证码" placeholder="请输入验证码" label-align="top"
            :rules="[{ required: true, message: '请填写验证码' }, { validator: codeRules }]">
            <template #button>
              <van-button size="small" type="primary" :disabled="codeInfo.isCodeSent" @click="sendCode">{{
                codeInfo.timer ? `${codeInfo.codeTime}秒` : '短信验证' }}</van-button>
            </template>
          </van-field>
          <!-- <van-field v-model="formData.nickname" name="nickname" label="昵称" placeholder="请输入昵称，2-10位字符"
            label-align="top" :rules="[{ required: true, message: '请填写昵称' }, { validator: nicknameRules }]" /> -->
        </van-cell-group>

        <div class="btnBox">
          <van-button round block type="primary" native-type="submit">
            注册
          </van-button>
        </div>

        <div class="flexBox flexcenterX mt30">
          <p class="fs28 c-666 f600 mr30">已有账户?</p>
          <RouterLink to="/login" class="fs28 c-main f600">立即登录</RouterLink>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { sendPhoneCode } from '@/api/common'
import { loginApi, phoneRegisterApi, registerApi } from '@/api/user'
import regConfig from '@/config/reg.config'
import router from '@/router'
import { userStore } from '@/store'
import { RegisterForm } from '@/types/userTypes'
import { debounce } from '@/utils'
import { setToken } from '@/utils/storage'
import { FieldRuleValidator, showToast } from 'vant'
import { reactive, ref } from 'vue'
import { RouterLink } from 'vue-router'
const formRef = ref()
const showPas = ref(false)
const curTab = ref(1)
const isPhone = ref(false)
const codeInfo = reactive({
  codeTime: 60,
  isCodeSent: false,
  timer: 0
})

const user = userStore()
const formData = reactive({
  account: '',
  password: '',
  phone: '',
  code: '',
  email: ''
})

const accountRules: FieldRuleValidator = (val: string) => {
  if (val.length < 5 || val.length > 32) {
    return '账号长度为5-32位'
  }
  if (!/^[a-zA-Z0-9_]+$/.test(val)) {
    return '账号只能包含字母、数字和下划线'
  }
  return true
}

const passwordRules: FieldRuleValidator = (val: string) => {
  if (val.length < 8 || val.length > 20) {
    return '密码长度为8-20位'
  }
  if (!/(?=.*[A-Za-z])(?=.*\d)/.test(val)) {
    return '密码必须包含字母和数字'
  }
  return true
}

// const nicknameRules: FieldRuleValidator = (val: string) => {
//   if (val.length < 2 || val.length > 10) {
//     return '昵称长度为2-10位'
//   }
//   if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(val)) {
//     return '昵称只能包含字母、数字和中文'
//   }
//   return true
// }

const phoneRules: FieldRuleValidator = (val: string) => {
  if (!regConfig.phone.test(val)) {
    return '请输入正确的手机号'
  }
  return true
}

const emailRules: FieldRuleValidator = (val: string) => {
  if (!regConfig.email.test(val)) {
    return '请输入正确的邮箱'
  }
  return true
}

const codeRules: FieldRuleValidator = (val: number) => {
  if (!/^\d{6}$/.test(val.toString())) {
    return '请输入正确的验证码'
  }
  return true
}

const handleLoginType = (type: number) => {
  curTab.value = type
  // 清空表单数据
  formData.account = ''
  formData.password = ''
  formData.phone = ''
  formData.code = ''
  formData.email = ''
  // 重置验证码倒计时
  codeInfo.codeTime = 60
  codeInfo.isCodeSent = false
  codeInfo.timer = 0

  isPhone.value = type === 2
}

const sendCode = debounce(async () => {
  if (codeInfo.isCodeSent) {
    return false
  }
  if (!formData.phone) {
    return showToast('请输入手机号')
  }
  codeInfo.isCodeSent = true

  try {
    const { data } = await sendPhoneCode({ phone: formData.phone })
    if (data.code === 0) {
      showToast('短信已发送')
      codeInfo.codeTime = 60
      codeInfo.timer = window.setInterval(() => {
        codeInfo.codeTime--
        if (codeInfo.codeTime < 1) {
          window.clearInterval(codeInfo.timer)
          codeInfo.timer = 0
          codeInfo.codeTime = 60
          codeInfo.isCodeSent = false
        }
      }, 1000)
    } else {
      showToast(data.msg || '短信发送失败')
      codeInfo.isCodeSent = false
    }
  } catch (err) {
    showToast(err || '短信发送失败')
    codeInfo.isCodeSent = false
  }
}, 1000, true)

const onSubmit = async (values: RegisterForm) => {
  if (values) {
    const postFn = isPhone.value ? phoneRegisterApi : registerApi
    const { data } = await postFn(formData)
    if (data.code === 0) {
      showToast(`注册成功，即将为您自动登录`)
      const loginParams = {
        account: values.account,
        password: values.password
      }
      setTimeout(async () => {
        const { data } = await loginApi(loginParams)
        if (data.code === 0) {
          setToken(data.data.token)
          user.setUserInfo({ id: data.data.id })
          await user.getUserInfo()
          router.push('/')
        }
      }, 500)
    }
  }
}
</script>

<style lang="scss" scoped>
.registerBox {
  padding: 0 30px;
  padding-top: 280px;
  background: #F7F8FA;
  height: 100%;

  .tabs {
    .tabIn {
      padding: 0 10px;
      font-weight: bold;

      &:not(:last-child) {
        border-right: 1px solid #d8d8d8;
      }
    }
  }
}

h2 {
  font-size: 56px;
}

.btnBox {
  margin: 35px;
}

.van-divider {
  color: #6b7280;
}

.van-divider:before,
.van-divider:after {
  border-color: #d1d5db;
  border-top-width: 2px;
}

.van-cell-group--inset {
  margin: 0;
}

.van-field__control {
  border: 5px solid #d9d9d9 !important;
}

// 错误提示样式优化
:deep(.van-field__error-message) {
  color: #ff4d4f;
  font-size: 24px;
  margin-top: 8px;
}

.curTab {
  color: #ec6300;
}
</style>